package com.ajx.todo.project.adplatform.utils;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;


import org.fusesource.mqtt.client.Future;
import org.fusesource.mqtt.client.FutureConnection;
import org.fusesource.mqtt.client.MQTT;
import org.fusesource.mqtt.client.Message;
import org.fusesource.mqtt.client.QoS;
import org.fusesource.mqtt.client.Topic;


import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MqttClient {
    private static final String TAG = "MqttClient";
    private final static String CONNECTION_STRING = "tcp://172.21.1.148:61613";
    private final static String CONNECTION_CLIENT = "SJ6C92F8C0136C4277"; //主机串号
    private final static String CONNECTION_USERNAME = "sanjiang";
    private final static String CONNECTION_PASSWORD = "sanjiangmqtt";
    private final static boolean CLEAN_START = true;
    private final static short KEEP_ALIVE = 30;// 低耗网络，但是又需要及时获取数据，心跳30s
    //public static Topic[] topics = { new Topic("host/command/SJ6C92F8C0136C4277", QoS.EXACTLY_ONCE) };

    public final static long RECONNECTION_ATTEMPT_MAX = 6;
    public final static long RECONNECTION_DELAY = 2000;

    public final static int SEND_BUFFER_SIZE = 2 * 1024 * 1024;// 发送最大缓冲为2M

    public static void start(String clientId, Context context) {
        Log.e(TAG, "Mqtt客户端id: "+clientId );
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 创建MQTT对象
        MQTT mqtt = new MQTT();
        FutureConnection connection = null;
        try {
            mqtt.setClientId(clientId);
            // 设置mqtt broker的ip和端口
            mqtt.setHost(CONNECTION_STRING);
            mqtt.setUserName(CONNECTION_USERNAME);
            mqtt.setPassword(CONNECTION_PASSWORD);
            // 连接前清空会话信息
            mqtt.setCleanSession(CLEAN_START);
            // 设置重新连接的次数
            mqtt.setReconnectAttemptsMax(RECONNECTION_ATTEMPT_MAX);
            // 设置重连的间隔时间
            mqtt.setReconnectDelay(RECONNECTION_DELAY);
            // 设置心跳时间
            mqtt.setKeepAlive(KEEP_ALIVE);
            // 设置缓冲的大小
            mqtt.setSendBufferSize(SEND_BUFFER_SIZE);

            // 获取mqtt的连接对象BlockingConnection
            connection = mqtt.futureConnection();
            // MQTT连接的创建
            connection.connect();
            // 订阅相关的主题信息
            Topic[] topics = {new Topic("host/command/" + clientId, QoS.EXACTLY_ONCE)};
            connection.subscribe(topics);

            Log.e(TAG, "start: 连接成功了");

            while (true) {
                // 接收订阅的消息内容
                Future<Message> futrueMessage = connection.receive();
                Message message = futrueMessage.await();
                // 获取订阅的消息内容
                // 获取到服务端发送的指令进行相应的处理操作
                Log.e(TAG, "start: 收到mqtt命令" );
                System.out.println("MQTTClient Message Topic=" + message.getTopic() + " Content: " + new String(message.getPayload()) + " Time: " + sdf.format(new Date()));
                Log.e(TAG, "start: " + new String(message.getPayload()));

                //MqttCmdHelper.getInstance().parseMqttCmd(new String(message.getPayload()));
                Toast.makeText(context, new String(message.getPayload()), Toast.LENGTH_SHORT).show();
                // 签收消息的回执
                //message.ack();
                //Thread.sleep(2000);
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
